<template>
  <a-upload
      v-model:file-list="fileList"
      :list-type="uploadType === 'image' ? 'picture-card' :null"
      name="file"
      :custom-request="selfUpload"
      @change="handleChange"
  >
    <div v-if="fileList.length  <= props.limit && uploadType === 'image'">
      <plus-outlined/>
      <div style="margin-top: 8px">上传</div>
    </div>

    <a-button v-if="uploadType === 'file'">
      <upload-outlined></upload-outlined>
      文件上传
    </a-button>

  </a-upload>
</template>
<script lang="ts" setup>
import {ref, watch} from 'vue';
import {PlusOutlined, UploadOutlined} from '@ant-design/icons-vue';
import {nanoid} from "nanoid";
import {UploadChangeParam} from "ant-design-vue";

const fileList = ref([]);

const props = defineProps({
  modelValue: {
    type: [String, Array]
  },
  limit: {
    default: 5,
    type: Number
  },
  uploadType: {
    default: 'image',
    type: String
  }
})

const emits = defineEmits(['update:modelValue']);

watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    let count = 1
    const list = Array.isArray(newValue) ? newValue : newValue.split(',')
    fileList.value = list.map(item => {
      if (typeof item === 'string') {
        item = {
          name: nanoid(),
          status: 'done',
          url: item
        }
      }
      item.uid = item.uid || new Date().getTime() + count++
      return item
    })
  } else {
    fileList.value.length = 0
    return []
  }
}, {
  immediate: true,
  deep: true
})


//对上传的文件处理
function selfUpload({action, file, onSuccess, onError, onProgress}) {
  new Promise(resolve => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = () => {
      resolve(fileReader.result);
      file.url = fileReader.result;
      onSuccess(fileReader.result)
    }
  })
}

const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'done') {
    emits('update:modelValue', handleFIleList(info.fileList))
  }
  if (info.file.status === 'removed') {
    emits('update:modelValue', handleFIleList(info.fileList))
  }
};

function handleFIleList(files) {
  return files.map(x => x.url)
}

</script>

